<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>心电监测平台 - 主页面</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 font-sans">

  <!-- 顶部栏 -->
  <header class="bg-blue-600 text-white shadow p-4 flex justify-between items-center">
    <h1 class="text-xl font-semibold">🏥 可穿戴心电监测平台</h1>
    <div class="flex items-center space-x-4">
      <span>欢迎，<b>{{ username }}</b></span>
      <span class="
        flex items-center gap-1
        px-3 py-1 rounded-full text-sm font-semibold
        {% if role == 'superadmin' %}
          bg-purple-600 text-white
        {% elif role == 'admin' %}
          bg-blue-500 text-white
        {% elif role == 'doctor' %}
          bg-green-500 text-white
        {% else %}
          bg-gray-400 text-white
        {% endif %}
      ">
        {% if role == 'superadmin' %}
          🛡️ 超级管理员
        {% elif role == 'admin' %}
          ⚙️ 管理员
        {% elif role == 'doctor' %}
          🩺 医生
        {% else %}
          👤 用户
        {% endif %}
      </span>
      <a href="/logout" class="bg-white text-blue-600 px-3 py-1 rounded hover:bg-gray-100">退出</a>
    </div>
  </header>

  <!-- 页面布局 -->
  <div class="flex">

    <!-- 左侧菜单 -->
    <aside class="w-64 bg-white h-screen shadow-md p-5">
      <nav class="space-y-3">
        {% if role in ['superadmin', 'admin'] %}
          <a href="/devices" class="block p-3 rounded {% if active_tab == 'devices' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            ⚙️ 设备管理
          </a>
          <a href="/users" class="block p-3 rounded {% if active_tab == 'users' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            👥 用户管理
          </a>
          <a href="/ecg" class="block p-3 rounded {% if active_tab == 'ecg' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            📊 全部心电数据
          </a>
          <a href="/alerts" class="block p-3 rounded {% if active_tab == 'alerts' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            ⚠️ 异常报警
          </a>
        {% elif role == 'doctor' %}
          <a href="/patients" class="block p-3 rounded {% if active_tab == 'patients' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            🧑‍⚕️ 患者管理
          </a>
          <a href="/ecg" class="block p-3 rounded {% if active_tab == 'ecg' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            📈 心电数据分析
          </a>
          <a href="/alerts" class="block p-3 rounded {% if active_tab == 'alerts' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            ⚠️ 异常报警
          </a>
        {% else %}
          <a href="/devices" class="block p-3 rounded {% if active_tab == 'devices' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            📟 我的设备
          </a>
          <a href="/ecg" class="block p-3 rounded {% if active_tab == 'ecg' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            📈 我的心电数据
          </a>
          <a href="/alerts" class="block p-3 rounded {% if active_tab == 'alerts' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            ⚠️ 异常报警
          </a>
          <a href="/profile" class="block p-3 rounded {% if active_tab == 'profile' %}bg-blue-100{% endif %} text-gray-700 font-medium">
            👤 个人信息
          </a>
        {% endif %}
      </nav>
    </aside>

    <!-- 主内容 -->
    <main class="flex-1 p-6">

      {% if active_tab == 'devices' %}
      <!-- ✅ 设备管理 -->
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold text-blue-600">📟 设备管理</h2>
          <a href="/" class="text-blue-600 hover:underline">⬅ 返回</a>
        </div>

        {% if role in ['admin', 'superadmin'] %}
        <form method="get" action="/devices" class="flex items-center space-x-2 mb-6">
          <input type="text" name="owner" value="{{ search_owner }}" placeholder="搜索用户名"
                 class="border p-2 rounded focus:ring-2 focus:ring-blue-400 focus:outline-none">
          <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition">搜索</button>
          <a href="/devices" class="text-gray-500 hover:underline ml-2">重置</a>
        </form>
        {% endif %}

        <!-- 绑定设备按钮 -->
        <div class="mb-6 flex justify-end">
          <button onclick="openDeviceModal()"
                  class="bg-blue-600 text-white px-4 py-2 rounded-lg shadow hover:bg-blue-700 transition">
            ➕ 绑定设备
          </button>
        </div>

        <!-- 弹窗遮罩 -->
        <div id="deviceModal"
             class="fixed inset-0 bg-black bg-opacity-40 hidden items-center justify-center z-50">
          <div class="bg-white rounded-2xl shadow-xl w-96 p-6 relative animate-fadeIn">
            <h2 class="text-xl font-semibold text-blue-600 mb-4 flex items-center">
              <span class="mr-2">📟</span>绑定新设备
            </h2>

            <form id="deviceForm" method="post" action="/devices/add" class="space-y-4">
              <div>
                <label class="block text-gray-700 mb-1">设备 SN 编号</label>
                <input type="text" name="device_id" required
                       placeholder="请输入设备编号"
                       class="w-full border rounded px-3 py-2 focus:ring-2 focus:ring-blue-400 outline-none">
              </div>

              <div>
                <label class="block text-gray-700 mb-1">设备名称</label>
                <input type="text" name="name" required
                       placeholder="请输入设备名称"
                       class="w-full border rounded px-3 py-2 focus:ring-2 focus:ring-blue-400 outline-none">
              </div>

              <div class="flex justify-end gap-3 mt-6">
                <button type="button" onclick="closeDeviceModal()"
                        class="px-4 py-2 bg-gray-200 rounded hover:bg-gray-300 transition">
                  取消
                </button>
                <button type="submit"
                        class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition">
                  确定绑定
                </button>
              </div>
            </form>
          </div>
        </div>

        <!-- ✅ 动画与控制脚本 -->
        <script>
          function openDeviceModal() {
            const modal = document.getElementById('deviceModal');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
          }

          function closeDeviceModal() {
            const modal = document.getElementById('deviceModal');
            modal.classList.add('hidden');
            modal.classList.remove('flex');
          }

          // ✅ 提交成功后自动关闭并提示
          const form = document.getElementById('deviceForm');
          if (form) {
            form.addEventListener('submit', () => {
              setTimeout(() => {
                closeDeviceModal();
                alert("✅ 设备绑定成功！");
              }, 500);
            });
          }
        </script>

        <!-- 动画效果 -->
        <style>
          @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
          }
          .animate-fadeIn {
            animation: fadeIn 0.25s ease-out;
          }
        </style>


        <div class="bg-white rounded-xl shadow p-5">
          {% if devices|length == 0 %}
            <p class="text-gray-500 text-center">尚未绑定任何设备。</p>
          {% else %}
            <table class="min-w-full text-left border-collapse">
              <thead>
                <tr class="border-b text-gray-600">
                  <th class="p-2">设备编号</th>
                  <th class="p-2">设备名称</th>
                  {% if role in ['admin','superadmin'] %}<th class="p-2">所属用户</th>{% endif %}
                  <th class="p-2">状态</th>
                  <th class="p-2 text-right">操作</th>
                </tr>
              </thead>
              <tbody>
                {% for d in devices %}
                <tr class="border-b hover:bg-gray-50">
                  <td class="p-2">{{ d.device_id }}</td>
                  <td class="p-2">{{ d.name }}</td>
                  {% if role in ['admin','superadmin'] %}<td class="p-2">{{ d.owner or '未知' }}</td>{% endif %}
                  <td class="p-2">{{ '在线' if d.online else '离线' }}</td>
                  <td class="p-2 text-right">
                    {% if role in ['admin','superadmin'] %}
                      <a href="/devices/delete/{{ d.device_id }}" class="text-red-500 hover:text-red-700">删除</a>
                    {% else %}
                      <a href="/devices/delete/{{ d.device_id }}" class="text-red-500 hover:text-red-700">解绑</a>
                    {% endif %}
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          {% endif %}
        </div>

      {% elif active_tab == 'users' %}
      <!-- ✅ 用户管理 -->
        <div class="flex justify-between items-center mb-4">
          <h2 class="text-xl font-semibold text-blue-600">👥 用户管理</h2>
          <a href="/" class="text-blue-600 hover:underline">⬅ 返回</a>
        </div>
      {% if msg %}
      <div class="mb-4 p-2 bg-green-100 text-green-700 rounded text-center">
        {{ msg }}
      </div>
      {% endif %}
        <form method="get" action="/users" class="flex gap-2 mb-6">
          <input type="text" name="q" placeholder="搜索用户名" value="{{ search_q }}"
                 class="border p-2 rounded flex-1 focus:ring-2 focus:ring-blue-400 focus:outline-none">
          <button type="submit"
                  class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition">搜索</button>
          <a href="/users" class="text-gray-500 hover:underline ml-2">重置</a>
        </form>

        <div class="bg-white shadow rounded-xl p-5">
          {% if users|length == 0 %}
            <p class="text-gray-500 text-center">暂无用户</p>
          {% else %}
            <table class="min-w-full text-left border-collapse">
              <thead>
                <tr class="border-b text-gray-600">
                  <th class="p-2">用户名</th>
                  <th class="p-2">邮箱</th>
                  <th class="p-2">手机号</th>
                  <th class="p-2">角色</th>
                  <th class="p-2 text-right">操作</th>
                </tr>
              </thead>
              <tbody>
                {% for u in users %}
                <tr class="border-b hover:bg-gray-50">
                  <td class="p-2">{{ u.username }}</td>
                  <td class="p-2">{{ u.email or '未填写' }}</td>
                  <td class="p-2">{{ u.phone or '未填写' }}</td>
                  <td class="p-2">
                    <form method="post" action="/users/update_role" class="flex items-center gap-2">
                      <input type="hidden" name="username" value="{{ u.username }}">
                      <select name="role" class="border rounded p-1">
                        {% if role == 'superadmin' %}
                          <option value="user" {% if u.role == 'user' %}selected{% endif %}>普通用户</option>
                          <option value="doctor" {% if u.role == 'doctor' %}selected{% endif %}>医生</option>
                          <option value="admin" {% if u.role == 'admin' %}selected{% endif %}>管理员</option>
                        {% elif role == 'admin' %}
                          <option value="user" {% if u.role == 'user' %}selected{% endif %}>普通用户</option>
                          <option value="doctor" {% if u.role == 'doctor' %}selected{% endif %}>医生</option>
                        {% else %}
                          <option value="user" {% if u.role == 'user' %}selected{% endif %}>普通用户</option>
                        {% endif %}
                      </select>
                      <button class="bg-blue-500 text-white px-2 py-1 rounded hover:bg-blue-600 text-sm">修改</button>
                    </form>
                  </td>
                  <td class="p-2 text-right">
                    {% if u.username == username or u.role == 'superadmin' %}
                      <span class="text-gray-400 text-sm">删除</span>
                    {% else %}
                      <a href="/users/delete/{{ u.username }}" class="text-red-500 hover:text-red-700">删除</a>
                    {% endif %}
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>
          {% endif %}
        </div>

      {% elif active_tab == 'patients' %}
      <!-- ✅ 患者管理 -->
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-semibold text-blue-600">🧑‍⚕️ 患者管理</h2>
        <a href="/" class="text-blue-600 hover:underline">⬅ 返回</a>
      </div>
      <!-- ✅ 添加患者表单 -->
      <form method="post" action="/patients/add_by_phone" class="flex gap-2 mb-6">
        <input type="text" name="phone" placeholder="输入患者手机号添加"
               class="border p-2 rounded flex-1 focus:ring-2 focus:ring-blue-400 focus:outline-none" required>
        <button type="submit"
                class="bg-green-500 text-white px-4 py-2 rounded hover:bg-green-600 transition">
          ➕ 添加患者
        </button>
      </form>

      {% if msg %}
      <div class="mb-4 p-2 bg-blue-100 text-blue-700 rounded text-center">{{ msg }}</div>
      {% endif %}

      <form method="get" action="/patients" class="flex gap-2 mb-6">
        <input type="text" name="q" placeholder="搜索患者用户名" value="{{ search_q }}"
               class="border p-2 rounded flex-1 focus:ring-2 focus:ring-blue-400 focus:outline-none">
        <button type="submit"
                class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition">
          搜索
        </button>
        <a href="/patients" class="text-gray-500 hover:underline ml-2">重置</a>
      </form>

      <div class="bg-white shadow rounded-xl p-5">
        {% if patients|length == 0 %}
        <p class="text-gray-500 text-center">暂无患者</p>
        {% else %}
        <table class="min-w-full text-left border-collapse">
          <thead>
            <tr class="border-b text-gray-600">
              <th class="p-2">用户名</th>
              <th class="p-2">邮箱</th>
              <th class="p-2">手机号</th>
              <th class="p-2">所属医生</th>
              <th class="p-2 text-right">操作</th>
            </tr>
          </thead>
          <tbody>
            {% for p in patients %}
            <tr class="border-b hover:bg-gray-50">
              <td class="p-2">{{ p.username }}</td>
              <td class="p-2">{{ p.email or '未填写' }}</td>
              <td class="p-2">{{ p.phone or '未填写' }}</td>
              <td class="p-2">
                <form method="post" action="/patients/update_doctor" class="flex items-center gap-2">
                  <input type="hidden" name="username" value="{{ p.username }}">
                  <select name="doctor_id" class="border rounded p-1">
                    {% for d in doctors %}
                      <option value="{{ d.id }}" {% if p.doctor_id == d.id %}selected{% endif %}>
                        {{ d.username }}
                      </option>
                    {% endfor %}
                  </select>
                  <button class="bg-blue-500 text-white px-2 py-1 rounded hover:bg-blue-600 text-sm">修改</button>
                </form>
              </td>
              <td class="p-2 text-right">
                <a href="/patients/delete/{{ p.username }}" class="text-red-500 hover:text-red-700">删除</a>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
        {% endif %}
      </div>

      {% elif active_tab == 'ecg' %}
      <!-- ✅ 心电数据 -->
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-semibold text-blue-600">📈 心电数据</h2>
        <a href="/" class="text-blue-600 hover:underline">⬅ 返回</a>
      </div>

      <div class="bg-white shadow p-6 rounded-xl">
        {% if devices|length == 0 %}
          <p class="text-gray-500 text-center">当前没有可查看的设备。</p>
        {% else %}
          <table class="min-w-full text-left border-collapse">
            <thead>
              <tr class="border-b text-gray-600">
                <th class="p-2">设备编号</th>
                <th class="p-2">设备名称</th>
                {% if role in ['admin', 'superadmin'] %}
                  <th class="p-2">所属用户</th>
                {% elif role == 'doctor' %}
                  <th class="p-2">所属患者</th>
                {% endif %}
                <th class="p-2 text-right">操作</th>
              </tr>
            </thead>
            <tbody>
              {% for d in devices %}
              <tr class="border-b hover:bg-gray-50">
                <td class="p-2">{{ d.device_id }}</td>
                <td class="p-2">{{ d.name or '未命名' }}</td>
                {% if role in ['admin', 'superadmin'] %}
                  <td class="p-2">{{ d.owner or '未知' }}</td>
                {% elif role == 'doctor' %}
                  <td class="p-2">{{ d.owner or '未知患者' }}</td>
                {% endif %}
                <td class="p-2 text-right">
                  <a href="/ecg/{{ d.device_id }}" class="text-blue-600 hover:underline">查看</a>
                </td>
              </tr>
              {% endfor %}
            </tbody>
          </table>
        {% endif %}
      </div>

      {% elif active_tab == 'alerts' %}
      <!-- ✅ 异常报警 -->
      <div class="flex justify-between items-center mb-4">
        <h2 class="text-xl font-semibold text-red-600">⚠️ 异常报警</h2>
        <a href="/" class="text-blue-600 hover:underline">⬅ 返回</a>
      </div>

      <div class="bg-white shadow rounded-xl p-5">

        {% if role in ['doctor', 'admin', 'superadmin'] and not selected_user %}
        <!-- ✅ 第一级页面：报警用户列表 -->
          {% if alert_users|length == 0 %}
            <p class="text-gray-500 text-center">暂无报警用户</p>
          {% else %}
            <table class="min-w-full text-left border-collapse">
              <thead>
                <tr class="border-b text-gray-600">
                  <th class="p-2">用户名</th>
                  <th class="p-2">最近报警时间</th>
                  <th class="p-2">报警次数</th>
                  <th class="p-2 text-right">操作</th>
                </tr>
              </thead>
              <tbody>
                {% for u in alert_users %}
                <tr class="border-b hover:bg-gray-50">
                  <td class="p-2">{{ u.username }}</td>
                  <td class="p-2">{{ u.latest_alert.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                  <td class="p-2">{{ u.alert_count }}</td>
                  <td class="p-2 text-right">
                    <a href="/alerts?user={{ u.username }}" class="text-blue-600 hover:underline">查看详情</a>
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>

            <!-- 分页控制 -->
            {% if total_pages > 1 %}
            <div class="flex justify-center items-center gap-4 mt-4">
              <button id="prevPageUsers"
                      class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600"
                      {% if current_page == 1 %}disabled{% endif %}>
                上一页
              </button>

              <span>第 <span id="currentPageUsers">{{ current_page }}</span> / <span id="totalPageUsers">{{ total_pages }}</span> 页</span>

              <button id="nextPageUsers"
                      class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600"
                      {% if current_page == total_pages %}disabled{% endif %}>
                下一页
              </button>
            </div>
            {% endif %}
          {% endif %}

          <script>
            document.getElementById("prevPageUsers")?.addEventListener("click", () => {
              if ({{ current_page }} > 1) {
                window.location.href = "/alerts?page={{ current_page - 1 }}";
              }
            });
            document.getElementById("nextPageUsers")?.addEventListener("click", () => {
              if ({{ current_page }} < {{ total_pages }}) {
                window.location.href = "/alerts?page={{ current_page + 1 }}";
              }
            });
          </script>

        {% else %}
        <!-- 第二级页面：报警详情页（或普通用户） -->
          {% if alerts|length == 0 %}
            <p class="text-gray-500 text-center">暂无报警记录</p>
          {% else %}
            {% if role in ['doctor', 'admin', 'superadmin'] %}
            <div class="flex justify-between mb-4 items-center">
              <h3 class="text-lg font-semibold text-blue-600">
                报警用户：{{ selected_user }}
              </h3>
              <div class="flex items-center gap-4">
                <a href="/alerts" class="text-gray-500 hover:underline">⬅ 返回用户列表</a>
                {% if role == 'doctor' and selected_user %}
                  <button id="batchResolveBtn" data-username="{{ selected_user }}"
                          class="bg-green-500 text-white px-3 py-1 rounded hover:bg-green-600 transition">
                    ✅ 批量标记已处理
                  </button>
                {% endif %}
              </div>
            </div>
            {% endif %}

            <table class="min-w-full text-left border-collapse">
              <thead>
                <tr class="border-b text-gray-600">
                  <th class="p-2">时间</th>
                  {% if role in ['doctor', 'admin', 'superadmin'] %}
                    <th class="p-2">设备编号</th>
                  {% endif %}
                  <th class="p-2">报警内容</th>
                  <th class="p-2 text-right">处理情况</th>
                </tr>
              </thead>
              <tbody>
                {% for a in alerts %}
                <tr class="border-b hover:bg-gray-50 {% if a.resolved %}opacity-60{% endif %}">
                  <td class="p-2">{{ a.timestamp.strftime('%Y-%m-%d %H:%M:%S') }}</td>
                  {% if role in ['doctor', 'admin', 'superadmin'] %}
                    <td class="p-2">{{ a.device_id }}</td>
                  {% endif %}
                  <td class="p-2 text-red-600">
                    {# 不再直接跳转：用 data-record-id 调用 API 在当前页弹窗展示心电图 #}
                    {% if a.ecg_record_id %}
                      <a href="javascript:void(0);" class="text-red-600 hover:underline open-ecg"
                         data-record-id="{{ a.ecg_record_id }}" data-device="{{ a.device_id }}">
                         {{ a.message }}
                      </a>
                    {% else %}
                      <a href="javascript:void(0);" class="text-red-600 hover:underline no-ecg">
                        {{ a.message }}
                      </a>
                    {% endif %}
                  </td>
                  <td class="p-2 text-right">
                    {% if role == 'doctor' %}
                      {% if a.resolved %}
                        <span class="text-green-600">已处理</span>
                      {% else %}
                        <button onclick="markResolved({{ a.id }})"
                                class="text-blue-600 hover:underline">标记已处理</button>
                      {% endif %}
                    {% else %}
                      {% if a.resolved %}
                        <span class="text-green-600">已处理</span>
                      {% else %}
                        <span class="text-gray-400">待处理</span>
                      {% endif %}
                    {% endif %}
                  </td>
                </tr>
                {% endfor %}
              </tbody>
            </table>

            <!-- 分页控制 -->
            {% if total_pages > 1 %}
              <div class="flex justify-center items-center gap-4 mt-4">
                <button id="prevPage"
                        class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600"
                        {% if current_page == 1 %}disabled{% endif %}>
                  上一页
                </button>

                <span>第 <span id="currentPage">{{ current_page }}</span> / <span id="totalPage">{{ total_pages }}</span> 页</span>

                <button id="nextPage"
                        class="bg-blue-500 text-white px-3 py-1 rounded hover:bg-blue-600"
                        {% if current_page == total_pages %}disabled{% endif %}>
                  下一页
                </button>
              </div>
            {% endif %}
          {% endif %}

          {# ===== 弹窗（放在页面内） ===== #}
          <div id="ecgOverlay" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-60">
            <div class="bg-white rounded-2xl shadow-xl w-11/12 max-w-6xl p-6 relative">
              <h2 id="ecgTitle" class="text-center text-blue-700 font-semibold mb-4 text-lg">心电波形图</h2>
              <div id="ecgPlot" class="w-full h-[520px]"></div>
              <div class="flex justify-end mt-4">
                <label class="mr-auto flex items-center gap-2 text-sm text-gray-700">
                  缩放模式：
                  <select id="ecgZoomMode" class="border rounded px-2 py-1 text-sm">
                    <option value="xy">双轴缩放</option>
                    <option value="x">仅横轴缩放</option>
                    <option value="y">仅纵轴缩放</option>
                  </select>
                </label>
                <button id="ecgReset" class="bg-blue-500 text-white px-4 py-2 rounded mr-2">重置缩放</button>
                <button id="ecgClose" class="bg-gray-500 text-white px-4 py-2 rounded">关闭</button>
              </div>
            </div>
          </div>

          <script src="https://cdn.plot.ly/plotly-2.30.0.min.js"></script>
          <script>
            const SAMPLE_RATE = 250;

            // 打开弹窗并绘图
            async function openEcgModal(recordId, deviceId) {
              if (!recordId) { alert("该报警未绑定心电记录。"); return; }
              try {
                const res = await fetch(`/api/ecg_record/${recordId}`);
                const j = await res.json();
                if (j.error) { alert("未能获取心电记录：" + j.error); return; }
                if (!j.data || j.data.trim() === "") { alert("该记录无心电数据。"); return; }

                const vals = j.data.split(",").map(x => parseFloat(x)).filter(x => !isNaN(x));
                if (vals.length === 0) { alert("该记录数据为空。"); return; }

                // 构建时间轴，若 start_time 可用则以时间显示，否则以秒数显示
                let x = [];
                const startTime = j.start_time ? new Date(j.start_time) : null;
                if (startTime) {
                  x = vals.map((_, i) => new Date(startTime.getTime() + (i / SAMPLE_RATE) * 1000));
                } else {
                  x = vals.map((_, i) => i / SAMPLE_RATE);
                }

                // 标题
                const title = `设备 ${deviceId || j.device_id} - 记录 ${recordId} ${j.start_time ? " | " + j.start_time : ""}`;
                document.getElementById("ecgTitle").innerText = title;

                // 显示弹窗
                const overlay = document.getElementById("ecgOverlay");
                overlay.classList.remove("hidden");

                const trace = {
                  x: x,
                  y: vals,
                  mode: "lines",
                  line: { color: "rgb(16,185,129)", width: 1 },
                  hoverinfo: "x+y",
                  name: "心电信号"
                };

                const layout = {
                  margin: { l: 70, r: 30, t: 30, b: 60 },
                  xaxis: {
                    title: startTime ? "时间" : "时间 (秒)",
                    type: startTime ? "date" : "linear",
                    tickformat: startTime ? "%H:%M:%S" : undefined,
                    showgrid: true
                  },
                  yaxis: {
                    title: "电压 (mV)",
                    range: [-1.2, 1.2],
                    showgrid: true
                  },
                  plot_bgcolor: "white",
                  paper_bgcolor: "white",
                  dragmode: "pan"
                };

                const config = {
                  responsive: true,
                  displayModeBar: true,
                  scrollZoom: true,
                  modeBarButtonsToRemove: ["lasso2d","select2d"]
                };

                Plotly.newPlot("ecgPlot", [trace], layout, config);
              } catch (err) {
                console.error(err);
                alert("加载心电数据失败");
              }
            }

            // 关闭弹窗
            document.getElementById("ecgClose").addEventListener("click", () => {
              document.getElementById("ecgOverlay").classList.add("hidden");
              // 清空图表，释放内存
              try { Plotly.purge("ecgPlot"); } catch(e) {}
            });

            // 缩放模式切换（横/纵/双）
            document.getElementById("ecgZoomMode").addEventListener("change", function() {
              const mode = this.value;
              let fixedX = false, fixedY = false;
              if (mode === "x") fixedY = true;
              if (mode === "y") fixedX = true;
              Plotly.relayout("ecgPlot", {
                "xaxis.fixedrange": fixedX,
                "yaxis.fixedrange": fixedY
              });
            });

            // 重置缩放
            document.getElementById("ecgReset").addEventListener("click", () => {
              Plotly.relayout("ecgPlot", { "xaxis.autorange": true, "yaxis.range": [-1.2, 1.2] });
            });

            // 绑定每条报警的点击事件（打开弹窗）
            document.querySelectorAll(".open-ecg").forEach(el => {
              el.addEventListener("click", (e) => {
                const id = e.currentTarget.getAttribute("data-record-id");
                const dev = e.currentTarget.getAttribute("data-device");
                openEcgModal(id, dev);
              });
            });

            // 点击无记录的报警提示
            document.querySelectorAll(".no-ecg").forEach(el => {
              el.addEventListener("click", () => alert("该报警未绑定心电记录。"));
            });

            // 单条标记已处理（医生）
            function markResolved(alertId) {
              const currentPage = {{ current_page }};
              fetch(`/alerts/resolve/${alertId}`, { method: 'POST' })
                .then(() => {
                  window.location.href = `/alerts?page=${currentPage}{% if selected_user %}&user={{ selected_user }}{% endif %}`;
                });
            }
            window.markResolved = markResolved;

            // 批量处理（医生）
            document.getElementById("batchResolveBtn")?.addEventListener("click", () => {
              const uname = document.getElementById("batchResolveBtn").getAttribute("data-username");
              if (!confirm(`确定要将 ${uname} 的所有报警标记为已处理吗？`)) return;
              fetch(`/alerts/resolve_all/${uname}`, { method: 'POST' })
                .then(r => r.json())
                .then(j => { alert(`✅ ${j.message || '批量处理完成'}`); window.location.reload(); })
                .catch(() => alert("批量处理失败"));
            });

            // 分页按钮
            document.getElementById("prevPage")?.addEventListener("click", () => {
              if ({{ current_page }} > 1) {
                window.location.href = "/alerts?page={{ current_page - 1 }}{% if selected_user %}&user={{ selected_user }}{% endif %}";
              }
            });
            document.getElementById("nextPage")?.addEventListener("click", () => {
              if ({{ current_page }} < {{ total_pages }}) {
                window.location.href = "/alerts?page={{ current_page + 1 }}{% if selected_user %}&user={{ selected_user }}{% endif %}";
              }
            });
          </script>
        {% endif %}
      </div>


      {% elif active_tab == 'profile' %}
      <!-- ✅ 个人信息 -->
      <div class="bg-white shadow p-6 rounded-xl space-y-4 max-w-xl mx-auto">
        {% if msg %}
        <div class="p-2 bg-green-100 text-green-700 rounded text-center">{{ msg }}</div>
        {% endif %}

        <form action="/profile/update" method="post" class="space-y-4">
          <div>
            <label class="block text-gray-700 font-medium mb-1">用户名（不可修改）</label>
            <input type="text" value="{{ user.username }}" disabled
                   class="w-full border p-2 rounded bg-gray-100 text-gray-600">
          </div>

          <div>
            <label class="block text-gray-700 font-medium mb-1">邮箱</label>
            <input type="email" name="email"
             value="{{ user.email if user.email not in [None, '', 'None'] else '' }}"
             placeholder="请输入邮箱"
             autocomplete="off"
             autocorrect="off"
             autocapitalize="off"
             spellcheck="false"
             class="w-full border p-2 rounded focus:ring-2 focus:ring-blue-400 focus:outline-none">
          </div>

          {% if role == 'user' %}
          <div>
            <label class="block text-gray-700 font-medium mb-1">所属医生</label>
            <input type="text" value="{{ doctor_name or '未指定' }}" disabled
                   class="w-full border p-2 rounded bg-gray-100 text-gray-600">
          </div>
          {% endif %}

          <div>
            <label class="block text-gray-700 font-medium mb-1">手机号</label>
            <input type="text" name="phone"
                   value="{{ user.phone if user.phone else '' }}"
                   placeholder="请输入手机号"
                   class="w-full border p-2 rounded focus:ring-2 focus:ring-blue-400 focus:outline-none">
          </div>

          <div>
            <label class="block text-gray-700 font-medium mb-1">修改密码（至少6位）</label>
            <!-- ✅ 密码永远为空 -->
            <input type="password" name="password" value=""
                   placeholder="如不修改请留空"
                   class="w-full border p-2 rounded focus:ring-2 focus:ring-blue-400 focus:outline-none">
          </div>

          <div class="text-center">
            <button class="bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600 transition">
              保存修改
            </button>
          </div>
        </form>
      </div>


      {% else %}
      <!-- ✅ 欢迎页 -->
      {% if role in ['admin','superadmin'] %}
      <div class="bg-white shadow p-6 rounded-xl mt-10 max-w-4xl mx-auto">
        <h2 class="text-xl font-semibold text-blue-700 mb-4 text-center">📊 今日设备在线趋势</h2>
        <canvas id="deviceChart" height="120"></canvas>
      </div>

      <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
      <script>
        async function loadDeviceStats() {
          const res = await fetch("/admin/device_stats");
          const data = await res.json();

          const labels = data.map(d => d.hour);
          const values = data.map(d => d.count);

          new Chart(document.getElementById("deviceChart"), {
            type: "line",
            data: {
              labels: labels,
              datasets: [{
                label: "在线设备数量",
                data: values,
                borderColor: "#2563eb",
                backgroundColor: "rgba(37, 99, 235, 0.2)",
                fill: true,
                tension: 0.3,
                borderWidth: 2,
                pointRadius: 3,
                pointBackgroundColor: "#1d4ed8"
              }]
            },
            options: {
              scales: {
                x: {
                  title: { display: true, text: "时间（小时）" }
                },
                y: {
                  title: { display: true, text: "在线设备数量" },
                  beginAtZero: true,
                  min: 0,
                  suggestedMax: Math.max(100, Math.max(...values) + 10),
                  ticks: {
                    stepSize: 10
                  }
                }
              },
              plugins: {
                legend: { display: false }
              }
            }
          });
        }
        loadDeviceStats();
      </script>
      {% else %}
      <div class="text-center text-gray-600 mt-32">
        <h2 class="text-2xl font-semibold text-blue-700 mb-2">欢迎使用可穿戴心电监测平台 👋</h2>
        <p class="mt-3 text-gray-500">请选择左侧菜单进入功能页面。</p>
      </div>
      {% endif %}
      {% endif %}
    </main>
  </div>
<!-- ✅ 心电图弹窗 -->
<div id="ecgModal" class="hidden fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50">
  <div class="bg-white rounded-2xl p-6 shadow-xl w-11/12 max-w-6xl relative">
    <h2 id="ecgTitle" class="text-xl font-semibold text-blue-600 mb-4 text-center">📈 心电图查看</h2>
    <div id="ecgChart" class="w-full h-[480px]"></div>

    <div class="flex justify-end mt-4">
      <button onclick="closeEcgModal()"
              class="bg-gray-500 text-white px-4 py-2 rounded hover:bg-gray-600">关闭</button>
    </div>
  </div>
</div>

  <!-- ✅ 加载 Plotly -->
  <script src="https://cdn.jsdelivr.net/npm/plotly.js-dist@2.27.0/plotly.min.js"></script>

  <script>
  async function showEcgModal(deviceId, recordId) {
    console.log("🩺 加载心电数据:", deviceId, recordId);
    try {
      if (!recordId) {
        alert("该报警未绑定心电记录。");
        return;
      }

      // 调用后端API获取该条心电数据
      const res = await fetch(`/api/ecg_record/${recordId}`);
      const data = await res.json();

      if (!data.data) {
        alert("该记录暂无心电数据。");
        return;
      }

      // 解析数据
      const dataArr = data.data.split(",").map(v => parseFloat(v)).filter(v => !isNaN(v));
      const sampleRate = 250;  // 假设采样率250Hz
      const timeArr = dataArr.map((_, i) => i / sampleRate);

      document.getElementById("ecgTitle").innerText = `📈 设备 ${deviceId} - 记录 ${recordId}`;
      document.getElementById("ecgModal").classList.remove("hidden");

      // 绘制心电图
      Plotly.newPlot("ecgChart", [{
        x: timeArr,
        y: dataArr,
        mode: "lines",
        line: { color: "rgb(16,185,129)", width: 1 },
        name: "心电信号"
      }], {
        margin: { t: 40, l: 60, r: 30, b: 50 },
        xaxis: { title: "时间 (秒)" },
        yaxis: { title: "电压 (mV)" },
        title: "",
      }, {responsive: true, displaylogo: false, scrollZoom: true});
    } catch (err) {
      console.error(err);
      alert("加载心电数据失败！");
    }
  }

  function closeEcgModal() {
    document.getElementById("ecgModal").classList.add("hidden");
  }
  </script>

</body>
  <script>
    (function() {
      const urlParams = new URLSearchParams(window.location.search);
      const msg = urlParams.get('msg');

      if (!msg) return;

      let message = '';
      let type = 'success'; // 默认成功类型

      switch (msg) {
        case 'add_success':
          message = '✅ 设备绑定成功！';
          break;
        case 'device_exists':
          message = '❌ 绑定失败：设备编号已存在！';
          type = 'error';
          break;
        case 'device_name_exists':
          message = '❌ 绑定失败：设备名称已存在！';
          type = 'error';
          break;
        case 'invalid_format':
          message = '❌ 设备编号格式错误！应为 ECG + 年份4位 + 6位编号（共13位）。';
          type = 'error';
          break;
        case 'invalid_length':
          message = '❌ 设备编号长度必须为13位！';
          type = 'error';
          break;
        case 'name_too_long':
          message = '❌ 设备名称长度不能超过10个字符！';
          type = 'error';
          break;
        case 'device_not_found':
          message = '设备未找到！';
          type = 'error';
          break;
        case 'delete_success':
          message = '设备删除成功！';
          break;
        case 'permission_denied':
          message = '你没有权限删除此设备！';
          type = 'error';
          break;
        default:
          message = '';
      }

      if (message) {
        // ✅ 弹出提示
        alert(message);

        // ✅ 清除 URL 中的 msg 参数，防止刷新重复弹出
        const url = new URL(window.location);
        url.searchParams.delete('msg');
        window.history.replaceState({}, document.title, url.pathname);
      }
    })();
  </script>


</html>
